<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FileController extends Controller
{

    /**
     * @abstract file upload
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadFile(Request $request){
        //本地开发环境
//        $path = 'D:\laragon\www\yiliyuan\public\picture\\';
        //部署环境
        $path = '/var/www/html/yiliyuan/public/picture/';
        $fileinfo = $_FILES['file'];
        //判断错误号
        if($fileinfo['error']>0){
            switch($fileinfo['error']){
                case 1:$error="上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";break;
                case 2:$error="上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";break;
                case 3:$error="文件只有部分被上传。";break;
                case 4:$error="没有文件被上传。";break;
                case 6:$error="找不到临时文件夹";break;
                case 7:$error="文件写入失败";break;
                default:$error="未知错误，请稍后再试...";
            }
            return response()->json(['data' => $error],204);
        }
        //定义允许类型
        $typearr=array("image/jpeg","image/png");
        //判断类型
        if(count($typearr)>0){
            if(!in_array($fileinfo['type'],$typearr)){
                return response()->json(['data' => '不支持的文件类型，目前支持jpg,png,gif格式的图片'],204);
            }
        }
        //取后缀
        $ext=pathinfo($fileinfo['name'],PATHINFO_EXTENSION);
        //生成随机文件名
        do{
            $newname=date("YmdHis").rand(1000,9999).".".$ext;
        }while(file_exists($path.$newname));
        //判断是否上传成功
        if(is_uploaded_file($fileinfo['tmp_name'])){
            if(move_uploaded_file($fileinfo['tmp_name'],$path.$newname)){
                //部署环境
//                return response()->json(['data' => "https://www.yiliyuan.club\\picture\\".$newname],200);
                return response()->json(['data' => "http://localhost:8080\\picture\\".$newname],200);
            }else{
                return response()->json(['data' => '上传失败，请重试'],200);
            }
        }else{
            return response()->json(['data' => '位置错误，请重试'],200);
        }
    }
}
